package com.damuzee.lvyou.user.action;

import com.damuzee.core.web.WebErrors;
import com.damuzee.core.web.session.SessionProvider;
import com.damuzee.lvyou.user.service.UserRegService;
import com.google.code.kaptcha.Constants;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by karkaw on 14-2-17.
 */

@Controller
public class UserAction {

    @Resource
    private UserRegService userRegService ;


    @Resource
    private SessionProvider session;

    @RequestMapping(value = "/login.do", method = RequestMethod.GET)
    public String login(){
        return "/login";
    }

    @RequestMapping(value = "/register.do", method = RequestMethod.GET)
    public String register(){
        return "/register";
    }

    @RequestMapping(value = "save.do" ,method = RequestMethod.POST)
    public String save(String nickName,String userId,String password,String vcode,
                       HttpServletRequest request,ModelMap model){
        WebErrors errors = validateSubmit(nickName,userId, password, vcode, request);
        if (!errors.hasErrors()) {
            userRegService.saveRegUser(nickName,userId,password);
            return "/login";
        }
        // 登录失败
        errors.toModel(model);

        return "/register";
    }

    private WebErrors validateSubmit(String nickName,String userId, String password,
                                     String vcode, HttpServletRequest request) {
        WebErrors errors = WebErrors.create(request);

         errors.isOutOfLength(nickName,"error.nickName",1,10);
         errors.isOutOfLength(userId, "error.userId", 1, 100);
         errors.isOutOfLength(password, "error.password", 1, 32) ;

        //验证用户名是否重复了


        // 如果输入了验证码，那么必须验证；如果没有输入验证码，则根据当前用户判断是否需要验证码。
        if (!StringUtils.isBlank(vcode)) {
          /*  String codeString = (String)session.getAttribute(request, Constants.KAPTCHA_SESSION_KEY);
            if (!vcode.equals(codeString)) {

                errors.addErrorCode("error.vcode");
                return errors;
            }*/
        }
        return errors ;
    }

}
